package com.aacar.op.service.mem;


import com.aacar.op.dao.mem.MemDao;
import com.aacar.op.dao.order.OrderDao;
import com.aacar.op.entity.mem.Member;
import com.aacar.op.entity.order.Order;
import com.aacar.op.utils.MathUtil;
import com.aacar.op.utils.web.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import push.PushUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("memberService")
@Transactional
public class MemberServiceImpl implements MemberService{
	
	private static Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);
	
    @Autowired
    private MemDao memDao;

	@Autowired
	private OrderDao orderDao;

	@Override
	public Member get(Long id) {
		// TODO Auto-generated method stub
		return memDao.findOne(id);
	}

	@Override
	public int saveOrUpdate(Member entity) {
		// TODO Auto-generated method stub
		int ret;
        entity.auditObject();
        if (entity.isNew()) {
//            ret = memDao.insert(entity);
        	ret = -1;
        } else {
        	if(entity.getIntegral()!=0) {
        		Order orderParam = new Order();
				orderParam.setUserId(String.valueOf(entity.getId()));
				orderParam.setIntegral(MathUtil.disposeAmount(-entity.getIntegral()));
				orderDao.updateMember(orderParam);

				//插入会员积分记录
				orderParam.setIntegralRecordstype("4");
				orderParam.setPayIntegral(entity.getIntegral());
				orderDao.insertIntegralRecords(orderParam);

				Member member = memDao.findOne(Long.valueOf(orderParam.getUserId()));
				PushUtils.sendAndroidAndIOSUnicast(member.getDeviceType(),member.getDeviceTokens(),"已为您充积分"+entity.getIntegral()+"，积分余额为"+member.getIntegral(), "");


			}else{
				entity.setModifyTime(new Date());
				ret = memDao.update(entity);
			}


        }
        return 1;
	}

	@Override
	public int delete(Long id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public PageInfo<Member> getPage(Map<String, Object> params, Pageable pageable) {
		PageUtils.mergeSort(params, pageable);
        //pageNum(页码)从1开始,spring data common domain从0开始的.
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Member> pageContent = memDao.findAll(params);
        return new PageInfo(pageContent);
	}

	@Override
	public List<Member> getAllMem(Member member) {
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("status", "1"); // 状态 1 可用 2停用
		List<Member> allMember = memDao.findAll(params);
		return allMember;
	}


}
